<template>
  <Layout style="height: 100%" class="main">
    <Sider
      hide-trigger
      collapsible
      :width="200"
      :collapsed-width="64"
      v-model="collapsed"
      class="left-sider"
      :style="{ overflow: 'hidden' }"
    >
    
      <side-menu
        accordion
        ref="sideMenu"
        :active-name="activeName"
        :collapsed="collapsed"
        @on-select="turnToPage"
        :menu-list="menuList"
      >
        <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
        <div class="logo-con">
          <!-- <img v-show="!collapsed" :src="maxLogo" key="max-logo" /> -->
          <div v-show="!collapsed" class="logo-text">火食集管理系统</div>
          <img v-show="collapsed" :src="minLogo" key="min-logo" />
        </div>
      </side-menu>
    </Sider>
    <Layout>
      <Header class="header-con">
        <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
          <user :message-unread-count="unreadCount" :user-avatar="userAvatar" />
          <fullscreen v-model="isFullscreen" style="margin-right: 10px" />
        </header-bar>
      </Header>
      <Content class="main-content-con" style="position: relative">
        <Spin size="large" v-if="spinShow" fix style="height: 100%; position: absolute; left: 0; top: 0px"></Spin>
        <Layout class="main-layout-con">
          <!-- <div class="tag-nav-wrapper">
            <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag" />
          </div> -->          
          <Content class="content-wrapper">
            <div>
              <custom-bread-crumb :list="breadCrumbList"></custom-bread-crumb>
            </div>
            <div class="content-wrapper-keep">
              <keep-alive :include="cacheList">
                <router-view />
              </keep-alive>
            </div>
            <ABackTop :height="100" :bottom="80" :right="50" container=".content-wrapper"></ABackTop>
          </Content>
          <div class="footer" style="text-align: center; padding: 20px 0"></div>
        </Layout>
      </Content>
    </Layout>


  </Layout>
</template>

<script>
import SideMenu from './components/side-menu'
import HeaderBar from './components/header-bar'
import TagsNav from './components/tags-nav'
import User from './components/user'
import ABackTop from './components/a-back-top'
import Fullscreen from './components/fullscreen'
import Language from './components/language'
import ErrorStore from './components/error-store'
import { mapMutations, mapActions, mapGetters } from 'vuex'
import customBreadCrumb from './components/header-bar/custom-bread-crumb/custom-bread-crumb.vue'
import { getNewTagList, routeEqual } from '@/libs/util'
import routers from '@/router/routers'
import minLogo from '@/assets/images/logo-min.jpg'
import maxLogo from '@/assets/images/logo.png'
import './main.less'

import { menuNav } from '@/api/system/menu.js'

export default {
  name: 'Main',
  components: {
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop,
    customBreadCrumb
  },
  data () {
    return {
      collapsed: false,
      minLogo,
      maxLogo,
      activeName: '' /* 侧边栏 active */,
      isFullscreen: false,
      menuList: [],
      date: new Date().getFullYear()
    }
  },
  computed: {
    ...mapGetters(['errorCount']),
    spinShow () {
      return this.$store.state.app.spinShow
    },
    breadCrumbList () {
      return this.$store.state.app.breadCrumbList
    },
    tagNavList () {
      return this.$store.state.app.tagNavList
    },
    tagRouter () {
      return this.$store.state.app.tagRouter
    },
    userAvatar () {
      return this.$store.state.user.avatarImgPath
    },
    cacheList () {
      const list = [
        'ParentView',
        ...(this.tagNavList.length
          ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name)
          : [])
      ]
      return list
    },
    // menuList () {
    //   return this.$store.getters.menuList||[]
    // },
    local () {
      return this.$store.state.app.local
    },
    hasReadErrorPage () {
      return this.$store.state.app.hasReadErrorPage
    },
    unreadCount () {
      return this.$store.state.user.unreadCount
    }
  },
  methods: {
    ...mapMutations(['setBreadCrumb', 'setTagNavList', 'addTag', 'setLocal', 'setHomeRoute', 'closeTag']),
    ...mapActions(['getUserInfo']),
    turnToPage (route) {
      let { name, params, query } = {}
      if (typeof route === 'string') name = route
      else {
        name = route.name
        params = route.params
        query = route.query
      }
      if (name.indexOf('isTurnByHref_') > -1) {
        window.open(name.split('_')[1])
        return
      }
      this.$router.push({
        name,
        params,
        query
      })
    },
    handleCollapsedChange (state) {
      this.collapsed = state
    },
    handleCloseTag (res, type, route) {
      if (type !== 'others') {
        if (type === 'all') {
          this.turnToPage(this.$config.homeName)
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route)
          }
        }
      }
      this.setTagNavList(res)
    },
    handleClick (item) {
      this.turnToPage(item)
    },
    /**
       *  如果有 metaActiveName,则显示activeName
       */
    getActiveName () {
      if (this.$route.meta.activeName) {
        this.activeName = this.$route.meta.activeName
      } else {
        this.activeName = this.$route.name
      }
    },

    // 获取用户菜单（鉴权）
    getMenuList () {
      //  this.menuList.unshift({
      //     title: '首页',
      //     icon: 'md-home',
      //     name: 'home',
      //     meta: {
      //       icon: 'md-home',
      //       title: '首页',
      //       role: ['a1', 'a2'],
      //     },
      //   })
      //   this.setHomeRoute(routers)
      menuNav().then(res => {
        this.menuList = this.mapMenu(res.data.menuList)
        this.$store.commit('setPermissions', res.data.permissions)
        this.menuList.unshift({
          title: '首页',
          icon: 'md-home',
          name: 'home',
          meta: {
            icon: 'md-home',
            title: '首页',
            role: ['a1', 'a2'],
          },
        })
        this.setHomeRoute(routers)
      })
      this.getUserInfo().then(res=>{
        console.log(res)
      })
    },
    /**
       * 处理数据
       */
    mapMenu (data) {
      return data.map(item => {
        return {
          name: item.url,
          icon: item.icon,
          href: item.href || null,
          title: item.name,
          meta: {
            icon: item.icon,
            title: item.name,
            href: item.href || null
          },
          children: item.list && item.list.length > 0 ? this.mapMenu(item.list) : []
        }
      })
    }
  },
  watch: {
    $route (newRoute) {
      const { name, query, params, meta } = newRoute
      this.addTag({
        route: { name, query, params, meta },
        type: 'push'
      })
      this.setBreadCrumb(newRoute)
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute))
      this.getActiveName()
      this.$refs.sideMenu.updateOpenName(newRoute.name)
    }
  },
  mounted () {
    /**
       * @description 初始化设置面包屑导航和标签导航
       */
    this.getMenuList()
    this.setTagNavList()
    this.setHomeRoute(routers)
    this.getActiveName()
    const { name, params, query, meta } = this.$route
    this.addTag({
      route: { name, params, query, meta }
    })
    this.setBreadCrumb(this.$route)
    // 设置初始语言
    this.setLocal(this.$i18n.locale)
    // 如果当前打开页面不在标签栏中，跳到homeName页
    if (!this.tagNavList.find(item => item.name === this.$route.name)) {
      this.$router.push({
        name: this.$config.homeName
      })
    }
  },
  activated(){
    /**
       * @description 初始化设置面包屑导航和标签导航
       */
    this.getMenuList()
    this.setTagNavList()
    this.setHomeRoute(routers)
    this.getActiveName()
    const { name, params, query, meta } = this.$route
    this.addTag({
      route: { name, params, query, meta }
    })
    this.setBreadCrumb(this.$route)
    // 设置初始语言
    this.setLocal(this.$i18n.locale)
    // 如果当前打开页面不在标签栏中，跳到homeName页
    if (!this.tagNavList.find(item => item.name === this.$route.name)) {
      this.$router.push({
        name: this.$config.homeName
      })
    }
  }
}
</script>
